#!/usr/bin/env python 2.7
# -*- coding: utf-8 -*-
# @Time      :2019/4/10
# @Author    :breeze
# @Email     :wangbaoshan@bbdservice.com
# @File      :IC10_OperatUpaidLoanBal
# @Software  :PyCharm


'''eof
name:个人经营性未结清贷款余额
code:IC10_OperatUpaidLoanBal_2D
tableName:
columnName:
groups:个人征信模块
dependencies:IC_DSJ_2D
type:常用指标
datasourceType:在线指标
description:
eof'''

import json
import sys
import re
import datetime
import pandas as pd
from datetime import datetime

reload(sys)
sys.setdefaultencoding('utf-8')

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']


def getTable(data, tableName, occurTimes, iteratorTimes):
    '''
        获取表信息
        :param data:表上层的字典对象
        :param tableName:表的名字
        :param occurTimes:表出现的次数，如果是0代表此表可以不出现，如果是1代表此表必须出现
        :param iteratorTimes:下级字段出现的次数，如果是0代表下级字段可以不出现，如果是1代表下级字段必须出现
        :return:该表全部数据  返回[{}]为异常缺失，返回0为正常缺失，其他返回正常数组
        '''
    try:
        table = data.get(tableName)
        if occurTimes == 0:
            if table is None or (table == "" and iteratorTimes == 0):
                return 0
            elif isinstance(table, list) is False or len(table) == 0 or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
        if occurTimes == 1:
            if table == "" and iteratorTimes == 0:
                return 0
            if table is None or isinstance(table, list) is False or len(table) == 0 \
                    or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
    except:
        return [{}]


def floatCheck(str):
    try:
        float(str)
        return True
    except:
        return False


def operatUpaidLoanBal():
    data = IC_DSJ_2D.get('data')
    factor1 = []
    factor2 = []
    factor3 = []
    # 借贷账户信息 PDA[1.1]
    PDA = getTable(data, 'PDA', 1, 0)
    if PDA == [{}]:
        return u'缺失值'
    elif PDA == 0:
        return 0
    else:
        # 借贷账户信息单元 PD01[0.*]
        PD01 = getTable(PDA[0], 'PD01', 0, 1)
        if PD01 == [{}]:
            return u'缺失值'
        elif PD01 == 0:
            return 0
        else:
            for i in PD01:
                try:
                    # 基本信息段 PD01A[1.1]
                    PD01A = getTable(i, 'PD01A', 1, 1)
                    # 最新表现信息段 PD01B[1.1]
                    PD01B = getTable(i, 'PD01B', 1, 1)
                    if PD01A == [{}] or PD01B == [{}]:
                        continue
                    elif PD01A == 0 or PD01B == 0:
                        factor1.append(0)
                        factor2.append(0)
                        factor3.append(0)
                    else:
                        # 账号类型
                        PD01AD01 = PD01A[0].get("PD01AD01")
                        # 业务种类
                        PD01AD03 = PD01A[0].get("PD01AD03")
                        # 账户状态
                        PD01BD01 = PD01B[0].get("PD01BD01")
                        # 余额
                        PD01BJ01 = PD01B[0].get("PD01BJ01")
                        if PD01AD01 not in null_type_list and PD01AD03 not in null_type_list and PD01BD01 not in null_type_list:
                            if PD01AD01 == "D1" and (PD01AD03 == "41" or PD01AD03 == "52") \
                                    and (PD01BD01 != "3" and PD01BD01 != '5'):
                                if floatCheck(PD01BJ01):
                                    factor1.append(float(PD01BJ01))
                                else:
                                    factor1.append(None)
                            if PD01AD01 == "R1" and (PD01AD03 == "41" or PD01AD03 == "52") \
                                    and PD01BD01 != "3":
                                if floatCheck(PD01BJ01):
                                    factor2.append(float(PD01BJ01))
                                else:
                                    factor2.append(None)
                            if PD01AD01 == "R4" and (PD01AD03 == "41" or PD01AD03 == "52") \
                                    and PD01BD01 != "3":
                                if floatCheck(PD01BJ01):
                                    factor3.append(float(PD01BJ01))
                                else:
                                    factor3.append(None)
                            else:
                                factor1.append(0)
                                factor2.append(0)
                                factor3.append(0)
                        else:
                            continue
                except:
                    continue

    factor1 = [x for x in factor1 if x is not None]
    factor2 = [x for x in factor2 if x is not None]
    factor3 = [x for x in factor3 if x is not None]
    if len(factor1) == 0 and len(factor2) == 0 and len(factor3) == 0:
        return u'缺失值'
    else:
        factor1 = sum(factor1) if len(factor1) > 0 else 0
        factor2 = sum(factor2) if len(factor2) > 0 else 0
        factor3 = sum(factor3) if len(factor3) > 0 else 0
        return factor1 + factor2 + factor3


if __name__ == '__main__':
    file_obj = open(r'../../data/IC/IC10_OperatUpaidLoanBal/IC.json', 'r')
    content = file_obj.read()
    IC_DSJ_2D = json.loads(content, strict=False)
    aa = operatUpaidLoanBal()
    print aa

result = operatUpaidLoanBal()
